package com.selftest.web.interceptor;

import com.selftest.web.RequestHandlerHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 请求处理拦截器，主要获取 Handler
 * 通过 ThreadLocal 获取
 */
public class HandlerHolder implements HandlerInterceptor, RequestHandlerHolder {

    /**
     * 通过 ThreadLocal 来暂存和获取 Handler
     */
    private final ThreadLocal<Object> HANDLERS = new ThreadLocal<>();

    /**
     * 在请求是获取到 Handler 并存入 ThreadLocal
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HANDLERS.set(handler);
        return true;
    }

    /**
     * 从 ThreadLocal 获取 Handler
     * @return
     * @param <T>
     */
    @Override
    public <T> T getHandler(){
        return (T) HANDLERS.get();
    }

    /**
     * 获取 Handler 的方法
     * @return
     */
    @Override
    public Method getHandlerMethod() {
        Object handler = getHandler();
        if (handler instanceof HandlerMethod) {
            return ((HandlerMethod) handler).getMethod();
        } else if (handler instanceof Method) {
            return (Method) handler;
        }
        return null;
    }
}
